/* 批量导入客户实际配额
 * @Author: Setsuna
 * @Email: setsuna.xyz@qq.com
 * @FilePath: \src\pages\QuotaManage\QuotaImport\List\components\BatchImportExcel.tsx
 * @Date: 2023-10-08 18:12:20
 * @LastEditTime: 2023-10-08 19:49:17
 * @LastEditors: Setsuna
 */
import { Button, message, Row, Spin, Upload } from 'antd'
import React, { createRef } from 'react'
import quotaApis from '@/apis/AboutQuota'
import todoApi from '@/apis/TodoList/index'
import { downBlobFileXlsx } from '@/utils/methods'
import { http, IUdFormItem, UdForm, validators } from '@/lib'
import QuotaApprove from '@/components/getQuotaApprove'
import './approve.scss'
import ossHttp from '@/utils/oss'
import { WrappedFormUtils } from 'antd/lib/form/Form'
import TextArea from 'antd/lib/input/TextArea'
import UdSelect from '@/components/UdFormControls/UdSelect'
import udMainStore from '@/store/UdMain'
import dayjs from 'dayjs'
// import UdUploader from '@/components/UdUploader/Uploader'

export default class BatchImportExcel extends React.Component<any> {
  private brandList = udMainStore.brandList
  private labelCol: any = { span: 3 }
  public cRef = createRef<any>()
  form: WrappedFormUtils
  state = {
    fileList: [],
    fileCertificateList: [],
    downloading: false,
    workFlowList: [],
    checkPerson: [],
    uploading: false,
    stageNameList: [],
  }

  componentDidMount() {
    this.handChangeStageNameList(this.props.brandCode)
  }

  //上传前操作
  private beforeUpload = file => {
    console.log('file', file)
    if (this.state.fileList.length === 0) {
      const fileItem = {
        file,
        uid: file.uid,
        name: file.name,
        status: 'uploading',
        url: '',
      }
      ossHttp.put('settled-review/annex', file).then(res => {
        fileItem.url = res.url
        fileItem.status = 'done'
        this.setState({ fileList: [fileItem] })
      })
    } else {
      message.error('只能上传一个文件')
    }
    return false
  }

  //删除文件
  private onRemove = file => {
    let fileList = this.state?.fileList ?? []
    fileList = fileList.filter(fileItem => fileItem.uid !== file.uid)
    this.setState({ fileList }, () => {
      return true
    })
  }

  //上传附件前操作
  private beforefileCertificateUpload = file => {
    console.log('file', file)
    if (this.state.fileCertificateList.length < 3) {
      const fileItem = {
        file,
        uid: file.uid,
        name: file.name,
        status: 'uploading',
        url: '',
      }
      ossHttp.put('settled-review/annex', file).then(res => {
        fileItem.url = res.url
        fileItem.status = 'done'
        this.setState({ fileCertificateList: [...this.state.fileCertificateList, fileItem] })
      })
    } else {
      message.error('只能上传3个文件')
    }
    return false
  }

  //删除附件文件
  private onfileCertificateRemove = file => {
    let fileCertificateList = this.state?.fileCertificateList ?? []
    fileCertificateList = fileCertificateList.filter(fileItem => fileItem.uid !== file.uid)
    this.setState({ fileCertificateList }, () => {
      return true
    })
  }

  private handChangeStageNameList = (value?) => {
    this.handGetManageProdsPlan()
    if (value) {
      this.getWorkFlow()
    }
  }

  //批量导入根据品牌官司、考核年度获取考核阶段
  private handGetManageProdsPlan = () => {
    this.form.setFieldsValue({ stageName: undefined }, () => {
      this.setState({ stageNameList: [] }, () => {
        let { brandCode, stageYear } = this.form.getFieldsValue()
        http.get(quotaApis.getManageProdsPlan, { params: { brandCode, stageYear } }).then(res => {
          const { data = [] } = res
          const stageNameList = data.map(item => ({ value: item.id, title: item.stageProdName }))
          this.setState({
            stageNameList,
          })
        })
      })
    })
  }

  //下载模板
  private downloadTemplate = () => {
    this.form.validateFields((err, values) => {
      if (!err) {
        let { stageName = [] } = values
        this.setState({ downloading: true })
        http
          .get(quotaApis.getBatchImportExcelTemplate, {
            params: { ids: stageName.join(',') },
            responseType: 'arraybuffer',
          })
          .then(res => {
            if (!res.data.code) {
              downBlobFileXlsx(res.data, '批量导入实际配额模板')
            }
          })
          .finally(() => {
            this.setState({ downloading: false })
          })
      } else {
        console.log(err)
      }
    })
  }

  //获取审批角色
  private getWorkFlow = () => {
    this.setState({ workFlowList: [],checkPerson:[] }, () => {
      let { brandCode } = this.form.getFieldsValue()
      http.get(todoApi.getQuotaImportNextApprove, { params: { brandCode} }).then(res => {
        const { data } = res
        this.setState({ workFlowList: data })
      })
    })
  }

  //选择审批人
  private handShowQuotaApprove(index) {
    this.cRef.current.handelCeck(index)
  }

  private handGetPerson(value) {
    this.setState({ checkPerson: value })
  }

  private onOk = e => {
    this.form.validateFields((err, values) => {
      if (!err) {
        const { remark,stageName=[] } = values
        const { fileList, fileCertificateList } = this.state
        if (fileList.length === 0) {
          message.warn('请选择导入文件')
          return false
        }
        if (this.state.checkPerson.length === 0) {
          message.warn('请选择审批人')
          return false
        }
        this.setState({ uploading: true })
        e.drawerBtnLoading()
        const formData = new FormData()
        formData.append('file', fileList[0].file)
        let params: any = {}
        if (this.state.checkPerson.length > 0) {
          params['workflowReqVos'] = {
            name: 'candidateUsers',
            userId: [this.state.checkPerson[0].id],
            remark: remark,
          }
        }
        params['ids']=stageName
        params['quotaApplyDetailFileRespVoList'] = [{ name: fileList[0].name, url: fileList[0].url }]
        params['quotaApplyDetailCertificateRespVoList'] = [
          ...fileCertificateList.map(r => {
            return { name: r.name, url: r.url }
          }),
        ]

        formData.append('quotaApplyExcelHistoryReqVo', new Blob([JSON.stringify(params)], { type: 'application/json' }))
        http
          .post(quotaApis.quotaStageTransmitProdsImport, formData, { timeout: 1000 * 60 * 10 })
          .then(() => {
            message.success('操作成功')
            this.props.refresh()
            e.close()
          })
          .catch(() => {
            e.drawerBtnLoadingHide()
          })
          .finally(() => {
            this.setState({ uploading: false })
          })
      } else {
        console.log(err)
      }
    })
  }

  render() {
    let { stageNameList } = this.state
    let { stageYearList = [], brandCode } = this.props ?? {}
    let items: IUdFormItem[] = [
      {
        label: '品牌公司',
        id: 'brandCode',
        initialValue: brandCode,
        render: (
          <UdSelect
            showSearch
            allowClear={false}
            options={this.brandList}
            onChange={value => {
              this.handChangeStageNameList(value)
            }}
          />
        ),
      },
      {
        label: '考核年度',
        id: 'stageYear',
        initialValue: dayjs().year(),
        render: () => (
          <UdSelect
            options={stageYearList}
            showSearch={true}
            optionFilterProp="children"
            onChange={() => {
              this.handChangeStageNameList()
            }}
          />
        ),
      },
      {
        id: 'stageName',
        label: '考核阶段',
        rules: [validators.required],
        render: () => (
          <UdSelect mode="multiple" options={stageNameList} showSearch={true} optionFilterProp="children" />
        ),
      },
      {
        label: '备注信息',
        id: 'remark',
        render: <TextArea rows={3} maxLength={200} />,
      },
      {
        id: 'fileTemplate',
        label: '客户模板',
        render: (
          <Button
            type="primary"
            onClick={() => {
              this.downloadTemplate()
            }}
          >
            下载模板
          </Button>
        ),
      },
      {
        id: 'fileUpload',
        label: '导入文件',
        render: (
          <Upload
            showUploadList={true}
            accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
            fileList={this.state.fileList}
            beforeUpload={file => this.beforeUpload(file)}
            onRemove={file => this.onRemove(file)}
          >
            <Button type="primary">上传文件</Button>
          </Upload>
        ),
      },
      {
        id: 'fileCertificate',
        label: '附件',
        render: (
          <Upload
            showUploadList={true}
            accept="image/jpg,image/jpeg,image/png,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel,application/msword"
            fileList={this.state.fileCertificateList}
            beforeUpload={file => this.beforefileCertificateUpload(file)}
            onRemove={file => this.onfileCertificateRemove(file)}
          >
            <Button type="primary">上传附件</Button>
            <div className="ud-uploader-extra">支持扩展名：.jpg .png .xls .doc</div>
          </Upload>
        ),
      },
    ]
    return (
      <Spin
        spinning={this.state.uploading || this.state.downloading}
        tip={this.state.uploading ? '上传中，请稍后...' : '下载中，请稍后...'}
      >
        <UdForm getForm={form => (this.form = form)} labelCol={this.labelCol} items={items} />
        {/* <Row style={{ marginTop: 20, marginBottom: 20, fontSize: 12 }}>
          <Row>备注信息</Row>
          <Row style={{ marginTop: 10 }}>1：执行中状态，只能导入一次</Row>
          <Row style={{ marginTop: 10 }}>2：待执行状态，不限制导入次数。</Row>
        </Row> */}
        <h4>审批流程</h4>
        <div className="approve-wrap">
          <div className="node-name-wrap">
            <div className="approve-title">节点名称：</div>
            <span className="circle-point"></span>
            <div>{this.state.workFlowList[0]?.nodeName || '暂无流程模板'}</div>
          </div>
          <div className="person-name-wrap">
            <div className="approve-title">审批人:</div>
            <div
              className={this.state.checkPerson[0]?.realName ? 'add-plus-name' : 'add-plus'}
              onClick={() => {
                this.state.workFlowList[0] ? this.handShowQuotaApprove(0) : (() => {})()
              }}
            >
              {this.state.checkPerson[0]?.realName || '+'}
            </div>
          </div>
        </div>
        <QuotaApprove
          handCilck={this.handGetPerson.bind(this)}
          cRef={this.cRef}
          ids={this.state.workFlowList[0]?.roleIds}
        />
      </Spin>
    )
  }
}
